<template>
  <div v-loading="pageLoading" element-loading-text="初始化配置中, 请稍等...">
    <div class="flex justify-end">
      <el-button type="primary" @click="addChromeConfig"> 添加 </el-button>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="domain" label="域名" width="300" />
      <el-table-column prop="url" label="路径" width="180" />
      <el-table-column prop="account" label="账号" />
      <el-table-column prop="password" label="密码" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <div class="flex">
            <el-button size="small" :disabled="scope.row.disabled" @click="openChrome(scope.row)">
              启动
            </el-button>
            <el-button size="small" @click="modifyChrome(scope.row)"> 修改 </el-button>
            <el-button size="small" type="danger" @click="delChrome(scope.row.id)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="showDetail"
      :title="dialogTitle"
      width="500"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="px-[80px]">
        <el-form ref="formRef" :model="form" label-width="auto">
          <el-form-item
            label="名称"
            prop="name"
            :rules="{
              required: true,
              message: '请输入名称',
              trigger: 'blur'
            }"
          >
            <el-input v-model="form.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item
            label="域名"
            prop="domain"
            :rules="{
              required: true,
              message: '请输入域名',
              trigger: 'blur'
            }"
          >
            <el-input v-model="form.domain" placeholder="请输入域名" />
          </el-form-item>
          <el-form-item label="路径" prop="url">
            <el-input v-model="form.url" placeholder="请输入路径" />
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input v-model="form.account" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="密码" prop="passFword">
            <el-input v-model="form.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item>
            <div class="flex justify-center w-full">
              <el-button @click="closeDialog">取消</el-button>
              <el-button type="primary" @click="onConfirm"> 确定 </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ChromeConfigItem } from "@renderer/types/chromeList";
import { computed, onMounted, reactive, ref, toRaw } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
type TableItem = ChromeConfigItem & { disabled: boolean };
const formRef = ref<FormInstance>();
const operaType = ref<"create" | "modify">("create");
const showDetail = ref<boolean>(false);
const pageLoading = ref<boolean>(false);
const resetFormData = {
  name: "",
  domain: "",
  url: "",
  account: "",
  password: ""
};
const form = reactive<ChromeConfigItem>(resetFormData);
const configObj = {
  create: {
    title: "新增",
    invoke: "createChrome",
    message: "新增成功"
  },
  modify: {
    title: "修改",
    invoke: "updateChrome",
    message: "修改成功"
  }
};
const dialogTitle = computed(() => {
  return configObj[operaType.value].title;
});
const tableData = ref<TableItem[]>([]);
onMounted(async () => {
  await getChromeList();
  window.api.mainSendRenderer("closeBrowserPage", (id) => {
    const curIndex = tableData.value.findIndex((item) => item.id === id);
    tableData.value[curIndex].disabled = false;
  });
  window.api.mainSendRenderer("downloadChromeProgress", (value) => {
    pageLoading.value = value != 100;
    // process.value = value
    // if(value == 100) {
    //   const item = tableData.value[itemIndex]
    //   openChrome(item, itemIndex)
    // }
  });
});
// 获取Chrome列表数据
async function getChromeList() {
  pageLoading.value = true;
  const { code, data, message } = await window.api.invoke("getChromeList");
  pageLoading.value = false;
  if (code != 0) {
    ElMessage.error(message);
    return;
  }
  tableData.value = data;
}
function modifyChrome(itemData: ChromeConfigItem) {
  operaType.value = "modify";
  showDetail.value = true;
  Object.assign(form, itemData);
}
function addChromeConfig() {
  operaType.value = "create";
  showDetail.value = true;
  Object.assign(form, resetFormData);
}
function closeDialog() {
  showDetail.value = false;
  formRef.value?.resetFields();
}
function onConfirm() {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      pageLoading.value = true;
      let resData;
      if (operaType.value == "create") {
        resData = await window.api.invoke("createChrome", toRaw(form));
      }
      if (operaType.value == "modify") {
        resData = await window.api.invoke("updateChrome", form.id, toRaw(form));
      }
      pageLoading.value = false;
      if (resData.code != 0) {
        ElMessage.error(resData.message);
        return;
      }
      closeDialog();
      getChromeList();
    }
  });
}
async function openChrome(item: TableItem) {
  item.disabled = true;
  const resData = await window.api.invoke("puppeteerBrowser", toRaw(item));
  if (!resData) {
    toRaw(item).disabled = false;
  }
}
async function delChrome(id: string) {
  await window.api.invoke("deleteChrome", id);
  getChromeList();
}
</script>
